package com.sulent.frame.support.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;

/**
 * @ClassName IOUtils
 * @Description: TODO
 * @Author Submerge.
 * @Since 2025/4/10 17:15
 * @Version 1.0
 */
public class IOUtils {

    protected FileInputStream convertImgBase64ToFileInputStream(String imgBase64Str) {
        String cleanBase64 = imgBase64Str.replaceAll("\\s", "");
//        String base64Prefix = "data:image/png;base64,";
        String str = cleanBase64.substring(cleanBase64.indexOf(",")+1);
        // 解码 Base64 字符串
        byte[] decodedBytes =cn.hutool.core.codec.Base64.decode(str);

        // 将解码后的字节数组写入临时文件
        File tempFile = null;
        //File file = new File("temp.png");
        try {
            tempFile = File.createTempFile("temp", ".png");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            fos.write(decodedBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 返回临时文件的 FileInputStream
        try {
            return new FileInputStream(tempFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }


    protected BufferedImage convertImgBase64ToBufferedImage(String imgBase64Str) throws IOException {
        //// 去掉 "data:image/...;base64," 前缀
        imgBase64Str = imgBase64Str.substring(imgBase64Str.indexOf(",")+1);
        // 解码 Base64 字符串为字节数组
        byte[] imageBytes = Base64.getDecoder().decode(imgBase64Str);

        // 将字节数组转换为 BufferedImage 对象
        ByteArrayInputStream bis = null;
        try {
            bis = new ByteArrayInputStream(imageBytes);
            return ImageIO.read(bis);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (bis != null){
                bis.close();
            }
        }
        return null;
    }
}
